<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-3-12
 * Time: 上午9:52
 */

namespace api\modules\chedai\controllers;


use api\modules\chedai\tools\ApiTools;
use common\components\tools\Tools;
use common\models\credit_app\Order;
use common\models\credit_app\OrderAttachment;
use common\models\credit_app\OrderOwner;
use common\models\credit_app\OrderCert;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;
use yii\db\Exception;

/**
 * Class OrderController
 * @package api\modules\chedai\controllers
 */
class OrderController extends Controller
{
    /**
     * 修改订单基本信息
     * @desc post 一般o开头
     * @param int $order_id 客户订单号
     * @return array
     * @throws ErrorException
     * @throws Exception
     */
    public function actionSave($order_id)
    {
        $order = $this->_getOrder($order_id);
        if (!$order) {
            throw new ErrorException("没有找到客户订单!");
        }
        $order->load(\Yii::$app->request->post(), '');
        $x = $order->save(false);
        if (!$x) {
            throw new Exception(Tools::makeModelGetErrorsToStringAndGetIt($order));
        }
        $o['order'] = $order->toArray();
        return $o;
    }

    /**
     * 修改购车人信息
     * @desc post 一般o/ot/ct_开头 如果没有找到购车人信息，则直接添加
     * @param int $order_id 客户订单号
     * @return array
     * @throws ErrorException
     * @throws Exception
     */
    public function actionBuyerSave($order_id)
    {
        $order = $this->_getOrder($order_id);
        if (!$order) {
            throw new ErrorException("没有找到客户订单!");
        }
        $owner = $order->owner;
        $cert_vip = $order->certVip;
        if (!$owner) {
//            throw new ErrorException("没有找到购车人信息!");
            $owner = new OrderOwner();
            $owner->ot_oid = $order_id;
        }
        if (!$cert_vip) {
            throw new ErrorException("没有找到购车人本人征信信息!");
        }
        $post = \Yii::$app->request->post();
        $owner->load(ApiTools::setSerializeApiField($post, OrderOwner::$serialize_fields), '');
        $cert_vip->load(ApiTools::setSerializeApiField($post, OrderCert::$serialize_fields), '');
        if (isset($post['ct_detail'])) {
            $x = json_decode($post['ct_detail'], true);
            $x['ct_sign'] = serialize(json_decode($x['ct_sign'], true));
            $x['ct_video'] = serialize(json_decode($x['ct_video'], true));
            $cert_vip->ct_detail = serialize($x);
        }
        $trans = \Yii::$app->db_app->beginTransaction();
        try {
            if (!$owner->ot_house_loan) $owner->ot_house_loan = '0.00';
            if (!$owner->ot_house_refundmo) $owner->ot_house_refundmo = '0.00';
            if (!$owner->ot_house_price) $owner->ot_house_price = '0.00';
            if (!$owner->ot_house_acreage) $owner->ot_house_acreage = '0.00';
            if (!$owner->ot_stake) $owner->ot_stake = '0.00';
            if (!$owner->ot_income_month) $owner->ot_income_month = '0.00';
            if (!$owner->ot_checkin_date) $owner->ot_checkin_date = '0000-00-00';
            if (!$owner->ot_hiredate) $owner->ot_hiredate = '0000-00-00';
            $owner->save(false);
            $cert_vip->save(false);
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
            throw $e;
        }
        $o['order'] = $order->toArray();
        $o['cert_vip'] = ApiTools::showSerializeApiField($cert_vip->toArray(), OrderCert::$serialize_fields);
        $o['owner'] = ApiTools::showSerializeApiField($owner->toArray(), OrderOwner::$serialize_fields);
//        $o['attachment'] = ApiTools::showSerializeApiField($order->attachment->toArray(), OrderAttachment::$serialize_fields);
        return $o;
    }

    /**
     * 修改配偶信息
     * @desc post 一般ot开头
     * @param int $order_id 客户订单号
     * @return array
     * @throws ErrorException
     * @throws Exception
     */
    public function actionSpouseSave($order_id)
    {
        $order = $this->_getOrder($order_id);
        if (!$order) {
            throw new ErrorException("没有找到客户订单!");
        }
        $cert_spouse = $order->certSpouse;
        if (!$cert_spouse) {
            throw new ErrorException("没有找到购车人配偶征信信息!");
        }
        $post = \Yii::$app->request->post();
        $cert_spouse->load(ApiTools::setSerializeApiField($post, OrderCert::$serialize_fields), '');
        if (isset($post['ct_detail'])) {
            $x = json_decode($post['ct_detail'], true, 512);
            $x['ct_sign'] = serialize(json_decode($x['ct_sign'], true, 512));
            $x['ct_video'] = serialize(json_decode($x['ct_video'], true, 512));
            $cert_spouse->ct_detail = serialize($x);
        }
        $trans = \Yii::$app->db_app->beginTransaction();
        try {
            $cert_spouse->save(false);
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
            throw $e;
        }
        $o['order'] = $order->toArray();
        $o['cert_spouse'] = ApiTools::showSerializeApiField($cert_spouse->toArray(), OrderCert::$serialize_fields);
        $o['attachment'] = ApiTools::showSerializeApiField($order->attachment->toArray(), OrderAttachment::$serialize_fields);
        return $o;
    }

    /**
     * 修改担保人信息
     * @desc post 一般ot开头
     * @param int $order_id 客户订单号
     * @param int $guarantor_id 担保人id
     * @return array
     * @throws ErrorException
     * @throws Exception
     */
    public function actionGuarantorSave($order_id, $guarantor_id)
    {
        $order = $this->_getOrder($order_id);
        $cert_guarantor = OrderCert::findActiveOneGuarantorById($guarantor_id);
        if (!$cert_guarantor) {
            throw new ErrorException("没有找到担保人!");
        } else {
            $order = $cert_guarantor->order;
            if (!$order) {
                throw new ErrorException("没有找到客户订单!");
            }
            if ($cert_guarantor->order->o_id != $order_id) {
                throw new ErrorException("担保人与订单号不匹配");
            }
        }
        $post = \Yii::$app->request->post();
        $cert_guarantor->load(ApiTools::setSerializeApiField($post, OrderCert::$serialize_fields), '');
        if (isset($post['ct_detail'])) {
            $x = json_decode($post['ct_detail'], true, 512);
            $x['ct_sign'] = serialize(json_decode($x['ct_sign'], true, 512));
            $x['ct_video'] = serialize(json_decode($x['ct_video'], true, 512));
            $cert_guarantor->ct_detail = serialize($x);
        }
        $trans = \Yii::$app->db_app->beginTransaction();
        try {
            $cert_guarantor->save(false);
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
            throw $e;
        }
        $o['order'] = $order->toArray();
        $o['cert_guarantor'] = ApiTools::showSerializeApiField($cert_guarantor->toArray(), OrderCert::$serialize_fields);
        $o['attachment'] = ApiTools::showSerializeApiField($order->attachment->toArray(), OrderAttachment::$serialize_fields);
        return $o;
    }

    /**
     * 修改附件信息
     * @desc post 一般oa开头的附件直接保存
     * @param int $order_id 客户订单号
     * @param json $cert_data 担保人的sign及video信息:[{"ct_id":"", "ct_sign":"", "ct_video":""}]
     * @return array
     * @throws ErrorException
     * @throws Exception
     */
    public function actionAttachmentSave($order_id, $cert_data = null)
    {
        $order = $this->_getOrder($order_id);
        if (!$order) {
            throw new ErrorException("没有找到客户订单!");
        }
        $attachment = $order->attachment;
        if (!$attachment) {
//            throw new ErrorException("没有找到附件信息!");
            $attachment = new OrderAttachment();
            $attachment->oa_oid = $order_id;
            $attachment->oa_assets = serialize('');
            $attachment->oa_family = serialize('');
            $attachment->oa_sign = serialize('');
            $attachment->oa_video = serialize('');
            $attachment->oa_flowing = serialize('');
            $attachment->oa_other = serialize('');
            $attachment->oa_contract = serialize('');
            $attachment->oa_status = 'draft';
            $attachment->oa_dateline = time();
            $attachment->oa_singlecard = serialize('');
            $attachment->oa_cert = serialize('');
            if (!$attachment->save()){
                throw new ErrorException("attachment保存失败 ".var_export($attachment->errors, true));
            }
        }
        $post = \Yii::$app->request->post();
        $attachment->load(ApiTools::setSerializeApiField($post, OrderAttachment::$serialize_fields), '');
        if ($cert_data) {
            $certs = json_decode($cert_data, true, 512);
            if (!is_array($certs) && count($certs) == 0) {
                throw new ErrorException("cert_data格式不对，不能获取到信息!");
            }
        } else {
            $certs = [];
        }
        $trans = \Yii::$app->db_app->beginTransaction();
        try {
            $attachment->save(false);
            foreach ($certs as $k => $v) {
                $cert = OrderCert::findActiveOneById($v['ct_id']);
                $cert->ct_sign = serialize($v['ct_sign']);
                $cert->ct_video = serialize($v['ct_video']);
                $cert->save(false);
            }
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
            throw $e;
        }
        $o['order'] = $order->toArray();
        $o['attachment'] = ApiTools::showSerializeApiField($attachment->toArray(), OrderAttachment::$serialize_fields);
        return $o;
    }

    /**
     * @param $order_id
     * @return null|static|Order
     */
    private function _getOrder($order_id)
    {
        $order = \common\models\credit_app\Order::findActiveOneById($order_id);
        if ($order){
            if (!in_array($order->o_status, Order::getCanOptStatus())){
                throw new ErrorException("当前状态不允许操作");
            }
        }
        return $order;
    }

    /**
     * 提交初审单信息
     * @desc post 需要业务员以上权限提交
     * @param string $order_id 订单id
     * @return array
     */
    public function actionSubmitTrialInfo($order_id)
    {
        $order = $this->_getOrder($order_id);
        if (!$order) {
            throw new ErrorException("没有找到单子");
        }
        return $order->trialSubmit();
    }
}